﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Chambills.Present.Core
{
    /// <summary>
    /// Stores property information about a Type pertaining to PropertyChangedNotification
    /// In order to avoid repeated refelcetion
    /// </summary>

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable")]
    public class PropertyModelCache : Dictionary<string, PropertyModel>
    {
        public PropertyModelCache(Type type)
        {
            AddAllPropertiesFromType(type);
            AddDependentPropertyLinks();
        }

        private void AddDependentPropertyLinks()
        {
            foreach(var property in this.Values)
            {
              property.DependentProperties.AddRange(this.Values.Where(p => p != property && IsDependentOn(p, property)));
            }
        }

        private bool IsDependentOn(PropertyModel dependent, PropertyModel property)
        {
            return Attribute
                .GetCustomAttributes(dependent.Member, true)
                .OfType<DependsOnAttribute>()
                .Any(x => x.PropertyName == property.Name);
        }

        private void AddAllPropertiesFromType(Type type)
        {
            foreach(var property in type.GetProperties())
            {
               
                this[property.Name] = new PropertyModel(property);
            }
        }
    }
}